const { UNAUTHORIZATION } = require("../config/error.js");
const jwt = require("jsonwebtoken");
const { PRIVATE_KEY, PUBLIC_KEY } = require("../config/secret.js");
const axios = require("axios");
const { WX_APPID, WX_SECRET } = require("../config/miniprogram.js");
const { verifyBindByWxopenid } = require("../server/userServer.js");

// 验证token是否有效
const verifyAuth = async (ctx, next) => {
	// 1. 获取token
	const token = ctx.headers.authorization;

	if (!token) {
		return ctx.app.emit("error", UNAUTHORIZATION, ctx);
	}
	// 2. 验证token是否有效
	try {
		const res = jwt.verify(token, PRIVATE_KEY, { algorithms: ["RS256"] });
		// 将token 也保存在ctx的user对象
		ctx["user"] = res;
		console.log("ctx.user:", res);
		// await next();
	} catch (error) {
		console.log(error);
		ctx.app.emit("error", UNAUTHORIZATION, ctx);
	}
};

const wxLoginByCode = async (ctx, next) => {
	const { code } = ctx.request.body;

	const { data } = await axios.get(
		`https://api.weixin.qq.com/sns/jscode2session?appid=${WX_APPID}&secret=${WX_SECRET}&js_code=${code}&grant_type=authorization_code`
	);
	ctx.wx_openid = data.openid;

	// 查看此微信是否绑定过
	// 如果 有则返回绑定的userInfo  如果没有执行next
	const result = await verifyBindByWxopenid(ctx.wx_openid);
	if (!!result.length) {
		ctx.body = {
			code: 1,
			message: "当前微信已经绑定过账号~",
			data: result,
		};
	} else {
		await next();
	}
};

module.exports = { verifyAuth, wxLoginByCode };
